/**
 * 
 */
package sailing.ui.systemsetting;

import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.jdesktop.application.SingleFrameApplication;

import sailing.entity.AccountingSubject;
import sailing.entity.SubjectCategory;
import sailing.listener.UI;
import sailing.managers.AccountingSubjectManager;
import sailing.ui.base.CommonJDialog;
import cjlite.utils.RandomUtils;
import cjlite.utils.TypeConverter;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 * @author kevin
 * 
 */
public class NewAccountingSubjectDialog extends CommonJDialog {

	private static String[] btnCaptions = { "确定", "取消" };

	private JComboBox<SubjectCategory> cateComb;

	private JTextField codeTF, nameTF;
	private JTextArea descTA;
	private DefaultComboBoxModel<SubjectCategory> scComBoModel;

	private TypeConverter tc = new TypeConverter();

	private SubjectCategory preSc;

	private AccountingSubject editAS;

	private boolean requiredUpdate = false;

	public NewAccountingSubjectDialog(Window window, SingleFrameApplication application) {
		super(window, "添加会计科目", ModalityType.APPLICATION_MODAL, application);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.ui.base.CommonJDialog#initialContentPanel()
	 */
	@Override
	protected JPanel initialContentPanel() {
		JPanel root = new JPanel();

		root.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

		FormLayout layout = new FormLayout("right:pref,4dlu,f:100dlu,f:40dlu",
				"22dlu,2dlu,22dlu,2dlu,22dlu,2dlu,80dlu,2dlu,22dlu");

		root.setLayout(layout);

		CellConstraints cc = new CellConstraints();

		// row 1
		root.add(new JLabel("科目分类："), cc.xy(1, 1));
		cateComb = new JComboBox<SubjectCategory>();
		root.add(cateComb, cc.xy(3, 1));
		// row 3
		root.add(new JLabel("科目代码："), cc.xy(1, 3));
		codeTF = new JTextField();
		root.add(codeTF, cc.xy(3, 3));
		// row 5
		root.add(new JLabel("科目名称："), cc.xy(1, 5));
		nameTF = new JTextField();
		root.add(nameTF, cc.xy(3, 5));
		// row 7
		root.add(new JLabel("科目简要描述："), cc.xy(1, 7, CellConstraints.RIGHT, CellConstraints.TOP));
		descTA = new JTextArea();
		descTA.setRows(5);
		JScrollPane textaSP = new JScrollPane(descTA);
		root.add(textaSP, cc.xywh(3, 7, 2, 1));
		// // row 9
		// root.add(new JLabel("开户时间："), cc.xy(1, 9));
		// openTimeTF = new JTextField();
		// dateChooser = DateChooser.getInstance("yyyy-MM-dd");
		// dateChooser.register(openTimeTF);
		// root.add(openTimeTF, cc.xy(3, 9));

		this.setSize(470, 430);
		this.updateData();

		return root;

	}

	protected void preSetData() {
		if (this.preSc != null) {
			scComBoModel.setSelectedItem(this.preSc);
		}
	}

	private void updateData() {
		AccountingSubjectManager asm = this.getApplication().getContext().getIoc()
				.getInstance(AccountingSubjectManager.class);

		List<SubjectCategory> scList = asm.getSubjectCategoryList();

		SubjectCategory[] scs = scList.toArray(new SubjectCategory[scList.size()]);
		scComBoModel = new DefaultComboBoxModel<SubjectCategory>(scs);
		cateComb.setModel(scComBoModel);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.ui.base.CommonJDialog#performBtnClick(java.lang.String)
	 */
	@Override
	protected void performBtnClick(String btnCaption) {
		if (btnCaption.equalsIgnoreCase(btnCaptions[0])) {
			this.performOKAction();
		} else {
			this.performCancelAction();
		}
	}

	private void performCancelAction() {
		this.setVisible(false);
	}

	private void performOKAction() {
		if(this.requiredUpdate){
			performUpdate();
			return;
		}
		
		
		AccountingSubject as = new AccountingSubject();

		String msg = this.validateInput(as);

		if (msg != null && msg.trim().length() > 0) {
			JOptionPane.showMessageDialog(this, msg, "错误！", JOptionPane.ERROR_MESSAGE);
			return;
		}

		as.setId(RandomUtils.randomString16());
		as.setLevel(1);

		AccountingSubjectManager asm = this.getApplication().getContext().getIoc()
				.getInstance(AccountingSubjectManager.class);

		if (asm.save(as)) {
			JOptionPane.showMessageDialog(this, "添加成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
			this.setVisible(false);
			UI.refresh();
		} else {
			JOptionPane.showMessageDialog(this, "添加失败！", "错误！", JOptionPane.ERROR_MESSAGE);
		}

	}

	private void performUpdate() {
		AccountingSubject as = this.editAS;
		String msg = this.validateInput(as);

		if (msg != null && msg.trim().length() > 0) {
			JOptionPane.showMessageDialog(this, msg, "错误！", JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		AccountingSubjectManager asm = this.getApplication().getContext().getIoc()
				.getInstance(AccountingSubjectManager.class);
		
		if (asm.update(as)) {
			JOptionPane.showMessageDialog(this, "编辑成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
			this.setVisible(false);
			UI.refresh();
		} else {
			JOptionPane.showMessageDialog(this, "编辑失败！", "错误！", JOptionPane.ERROR_MESSAGE);
		}
	}

	private String validateInput(AccountingSubject as) {
		StringBuilder sb = new StringBuilder();
		SubjectCategory sc = (SubjectCategory) this.cateComb.getSelectedItem();
		as.setParentId(String.valueOf(sc.getCode()));

		String value = this.codeTF.getText();
		if (value == null || value.trim().length() == 0) {
			sb.append("+ 请输入科目代码！\n");
		} else {
			try {
				as.setCode(tc.convert(int.class, value));
			} catch (Exception e) {
				sb.append("+ 科目代码必须为数字！\n");
			}
		}

		value = this.nameTF.getText();
		if (value == null || value.trim().length() == 0) {
			sb.append("+ 请输入科目名称！\n");
		} else {
			as.setName(value);
		}

		as.setDesc(this.descTA.getText());

		return sb.toString();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.ui.base.CommonJDialog#getBottomBtnTxt()
	 */
	@Override
	protected String[] getBottomBtnTxt() {
		return btnCaptions;
	}

	public void setPreSubjectCategory(SubjectCategory subjectCategory) {
		this.preSc = subjectCategory;
	}

	public void setPreSubject(AccountingSubject as) {
		this.editAS = as;
		this.requiredUpdate = true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.ui.base.CommonJDialog#getTopMessage()
	 */
	@Override
	protected String getTopMessage() {
		if (!this.requiredUpdate) {
			return null;
		}
		return "编辑会计科目";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.ui.base.CommonJDialog#preUpdateUIData()
	 */
	@Override
	protected void preUpdateUIData() {
		preSetData();

		if (this.editAS != null) {
			this.codeTF.setText(String.valueOf(this.editAS.getCode()));
			this.nameTF.setText(this.editAS.getName());
			this.descTA.setText(this.editAS.getDesc());
		}
	}

}
